package com.guess.lolguessing.service.impl;

import com.guess.lolguessing.domain.po.StarComment;
import com.guess.lolguessing.mapper.StarCommentMapper;
import com.guess.lolguessing.service.IStarCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-17
 */
@Service
public class StarCommentServiceImpl extends ServiceImpl<StarCommentMapper, StarComment> implements IStarCommentService {

    @Override
    public StarComment getByMatchIdAndTeamId(Integer matchId, Integer playerId) {
        StarComment one = this.lambdaQuery().eq(StarComment::getMatchId, matchId)
                .eq(StarComment::getPlayerId, playerId).one();
        return one;
    }

    @Override
    public void updateRating(Integer matchId, Integer playerId, Integer rating) {
        // 使用 for update 加锁读取
        StarComment one = this.lambdaQuery()
                .eq(StarComment::getMatchId, matchId)
                .eq(StarComment::getPlayerId, playerId)
                .last("for update") // 加悲观锁
                .one();

        if (one == null) {
            throw new IllegalArgumentException("记录不存在");
        }
        if(rating != 0) {
            one.setStarNum(one.getStarNum() + 1);
            one.setTotal(one.getTotal() + rating);
        }
        this.updateById(one); // 在事务中更新
    }

}
